Repository navigation
Keep the Python object of a __namespace__ subclass of a .NET exception - #167
Conversation
There was a problem hiding this comment.
Approving. I checked the root cause: ClassManager picked ExceptionClassObject before checking for the generated __pyobj__ field, so generated exception types never got ClassDerivedObject.NewObjectToPython or its tp_dealloc/tp_clear lifetime handling. The fix moves the derived-type check first, so it only affects generated types. For every other type, GetPyObjField returns null and the type falls through to the same branch as before. The new ExceptionClassDerivedObject keeps the exception tp_repr/tp_str and the args/__cause__ refresh after __init__. Slot lookup walks the implementing type's hierarchy from the most derived class, so the new static slots win over ClassBase's, as the comment says.
What I verified
-
CI is green on all jobs, including the Lean regression and unit test runs. The new test ran in every Python job (
test_exceptions.pyshows 30 passed, none skipped). -
Locally, master installed in its own venv vs this branch (Python 3.11, .NET 10). The new test's script segfaults (rc 139) on master and passes on the branch. I also probed namespaced subclasses of
System.Exceptionon both:- a plain one constructed with a message
- a Python subclass of a namespaced one, raised and caught as itself
- one thrown from .NET with
ExceptionDispatchInfo.Throwand caught in Python as the same object - 20k raise/catch iterations with Python and .NET GC: stable memory
- a traceback whose frame locals reference other objects: those objects are freed after GC
All of these crash on master and pass on the branch.
-
End to end: I ran a Lean Python backtest with this build. Its algorithm defines
__namespace__subclasses ofSystem.ArgumentExceptionwithout__init__, with an__init__that skipssuper()plus aToStringoverride, and withsuper().__init__("message"). For each, it checks the round-trip throughList[Object], identity onraise,str()andargs. All checks passed.
Notes (non-blocking, not caused by this change)
- A Python
__str__/__repr__on a namespaced exception subclass is ignored:str()returns the .NET message. Namespaced subclasses ofSystem.Objectbehave the same way on this branch, so this matches the other derived types. - When a namespaced exception is the
InnerExceptionof a .NET exception converted to Python,__cause__is a second wrapper:outer.__cause__ is innerisFalse. That comes fromExceptions.SetArgsAndCauseusingCLRObject.GetReferenceinstead ofConverter.ToPython. Because the second wrapper now getsClassDerivedObject.tp_dealloc, which never frees it, each such conversion keeps roughly 200 bytes. Master crashes before it gets this far, so this change doesn't make it worse. A follow-up could switch that call toConverter.ToPython.
Other repositories: Lean picks this up through its pythonnet package reference, so it needs a version bump after release. No other repository needs a code change.
Risk: I set risk:low. The change is small and easy to revert. It only changes behaviour for generated (__namespace__) exception types, which crash on master. A regression test fails without the fix, CI is green including Lean's suites, and the end-to-end run passed. There's no public API change.
There was a problem hiding this comment.
The construction fix addresses the reported failure, but I reproduced regressions in cases that current master handles without crashing. Please address both findings in the inline comments before merging:
- Derived lifetime handling is not safe for exceptions: two generated inheritance levels can enqueue and free the same Python wrapper twice (SIGSEGV), and the inherited no-op
tp_clearleaves native exception-field cycles permanently retained. - A Python
ToString()failure escapestp_str:str(error)aborts the process rather than producing a catchable Python exception. This also reproduced end to end in a Lean Python backtest.
Verification: all nine CI checks are green. Locally on Python 3.11 / .NET 10, the full Python suite passed (487 passed, 23 skipped), embedding tests passed (1049 passed, 8 skipped, plus the isolated SetPythonPath test), and the managed Python runner passed (2/2). Its first run failed because an unrelated installed tests package shadowed this repository; it passed after correcting the module search path. The new subprocess regression crashes on master and passes on this head. The additional minimal probes instead demonstrate master exiting normally versus this head aborting during formatting or segfaulting during multilevel finalization; cause-cycle collection leaves 0 exceptions on master versus 100 on this head. Green existing tests therefore do not cover the failing paths.
Follow-up: .NET-created generated exceptions also retain pre-constructor args and omit their cause. Master already aborts on that construction/return path, so I filed #168 separately rather than treating it as another regression blocker.
Affected repositories: Lean needs its pythonnet package references updated after a corrected release; no caller-side API change is needed for these fixes.
Risk: I set risk:high, replacing risk:low, because the new lifetime/formatting paths introduce verified native process crashes and unreclaimed exceptions. Passing subprocess tests for these cases, including draining the derived-finalization queue and asserting collection rather than only survival, plus an end-to-end run without the formatting abort, would materially lower that risk.
|
Addressed the requested changes in e491af1 (description updated):
Full suite: embedding tests 1049 passed, 8 skipped, plus 1 passed (SetPythonPath); pytest 488 passed, 23 skipped; Python test runner 2 passed. An end-to-end Lean Python backtest covering all three cases passed. The .NET-created case reported in #168 stays separate. So does the second |
There was a problem hiding this comment.
Requesting changes. The two fixes for the earlier findings work, but the cause behind the ToString finding is still there in two more slots.
What changed since my last review (e491af1)
PyFinalizenow queues each object once. Every generated level declares its own private__pyobj__, butGetPyObjField(obj.GetType())always resolves the most derived type's field, so all levels read and clear the same field.AddDerivedFinalizedObjectcopies the pointer beforeSetPyObjclears the field, and nothing reads the field after that. The guard also prevents theArgumentNullExceptionthat an empty field used to throw on the finalizer thread. Resolved.ExceptionClassDerivedObject.tp_clearbreaksargs/__cause__/__context__cycles. Resolved. One trade-off: it also clears__dict__on an exception that .NET still holds. NamespacedSystem.Objectsubclasses already lose__dict__the same way on master, so this matches them rather than making things worse. I opened #169 for that, and it doesn't block this change.ExceptionClassObject.tp_strnow raises theToStringerror tostr()'s caller, the same wayClassBase.tp_strdoes. Resolved.
Finding (blocking): Python overrides reached from the other exception slots can still abort the process. The wrapper is valid now, so the slots that ExceptionClassDerivedObject takes from ExceptionClassObject also reach Python overrides of virtual members. The previous commit guarded only tp_str. tp_repr reads e.Message, and Init calls Exceptions.SetArgsAndCause, which reads e.Message too. Neither catches errors, so a Python get_Message that raises escapes the native slot. I tested both on Python 3.11 / .NET 10, master vs this head:
repr(error)for a subclass withdef __init__(self): passand a raisingget_Message: master prints the base message and exits 0. This head aborts with exit 134 (Unhandled exception. Python.Runtime.PythonException).- The same subclass with
super().__init__(): on master, construction succeeds. On this head it aborts with exit 134.
These have the same cause as the ToString finding, so guard every exception slot that runs managed code, not one slot per review. In practice, wrap the managed calls in ExceptionClassObject.tp_repr and ExceptionClassDerivedObject.Init in the try/catch that tp_str now uses, and extend test_namespaced_exception_subclass_release to check that the ValueError reaches the caller of repr() and of the constructor. Details inline.
Verification: all nine CI checks are green on e491af1, including both Lean jobs. I built master and this head in separate environments and ran the probes above. I also checked the cycle and chain fixes against the code paths described above.
Other repositories: after release, Lean needs its pythonnet package reference bumped. No other code changes are needed.
Risk: stays risk:high. This head still aborts the process in cases that exit normally on master: repr() and construction with a raising get_Message override. With both guarded and covered by the subprocess test, the remaining evidence (green CI, regression tests that fail without each fix, the end-to-end runs) would support a lower rating.
|
Addressed the review in d282ec1 (description updated):
Full suite: embedding tests 1049 passed, 8 skipped, plus 1 passed (SetPythonPath); pytest 488 passed, 23 skipped; Python test runner 2 passed. Tested end to end in a Lean Python backtest: both The |
- A __namespace__ subclass of another one has a generated Finalize at each level, all calling PythonDerivedType.PyFinalize on the same object, which queued the same Python object once per level for release: freed twice, the process crashed. PyFinalize now clears the object's __pyobj__ field once it queued it, and skips an object it already queued. This also fixes chains of __namespace__ subclasses of System.Object. - The derived types' tp_clear is a no-op, so an exception referencing itself through args, __cause__, __context__ or __traceback__ was never collected. A __namespace__ exception subclass now clears those fields, keeping its wrapper for the .NET object. - A Python ToString override that raised escaped the exception str() slot and aborted the process; its error is now raised to str()'s caller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A __namespace__ exception subclass's Python overrides are reached from .NET now, so a Message override that raised escaped tp_repr, and __init__ through Exceptions.SetArgsAndCause, aborting the process. Both now raise the error to the caller, as tp_str does for ToString. The exception Init of reflected and generated types shares the guarded SetArgsAndCause call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- tp_str and tp_repr of exceptions now run all their work inside the guard: a Python ToString override returning None crashed on the prefix stripping after the guarded call. None now reads as an empty message. - The guards raised the InnerException of the caught error, which for a Python override's error is its __cause__: raise ValueError() from KeyError() reached the caller as KeyError. ToString and Message are called directly here, so the error is raised as it is. - The override error cases move to their own subprocess test, which constructs the exception before its overrides start failing, so repr() is reached, and checks each error's type and cause. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A generated type's Finalize released the Python object before calling its base class finalizer, and since releasing became once only it clears __pyobj__: a base finalizer calling a virtual member then no longer reached the Python override (the .NET implementation ran, or an abstract one threw and terminated the process). Finalize now runs the base finalizer first: the innermost generated type queues the Python object once the finalizer chain ran, and the outer ones skip it. - An inherited ToString runs through reflection, which wraps the error of a Python Message override it calls in a TargetInvocationException. The exception slots now raise that wrapper's inner error, and still raise a PythonException as it is, with its cause. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each generated __namespace__ level that an inherited member runs through adds its own TargetInvocationException, so with two levels str() raised one of them instead of the Python override's error. ExceptionClassObject's SetError now unwraps all of the leading wrappers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Done in d62a333, and rebased on master:
|
There was a problem hiding this comment.
Approving. d62a333 does what was asked in the last comment, and I found nothing new.
What changed since my last review (2c5dc3b)
- Rebase on master: the only conflict, in
src/testing/constructortests.cs, keeps bothCountedConstructorTestand the finalizer fixtures. The other commits are unchanged. - Inherited formatting through several
__namespace__levels:ExceptionClassObject.SetErrornow unwraps every leadingTargetInvocationExceptionand stops at the first non-wrapper. APythonExceptiontherefore still keeps itsInnerExceptionas the cause. This resolves the remaining open finding about errors restored through two or more levels. - Description: it now lists three subprocess tests and has its own section for the two master bugs that the
PyFinalizeguard and the newFinalizeorder fix.
What I verified
- All nine CI checks pass on d62a333, including the Lean regression and unit-test jobs. The three new subprocess tests ran there and weren't skipped.
- Locally on Python 3.11 / .NET 10 with this head built:
pytest --runtime netcore tests492 passed, 23 skipped. That includestest_subclass.pyfrom #180, which this change now sits on. - With only the old single unwrap restored,
test_namespaced_exception_subclass_override_errorsfails:str()raisesTargetInvocationException. With the loop it passes. - Extra probes on
__namespace__subclasses ofSystem.ArgumentException, one, two and three levels deep, each with a raisingget_Message.str()andrepr()both raise theValueErrorwith itsKeyErrorcause. They do the same for a child that inherits its parent's Pythonget_Message, which #180 now makes reachable. Reflected exceptions keep theirstr()/repr(). - End to end, I ran a Lean Python backtest with this runtime. It checks one, two and three levels of inherited
ToStringraising aget_Messageoverride'sValueErrorwith itsKeyErrorcause. It also checks that a subclass without__init__round-trips and is raised as itself, and it releases two-level chains ofSystem.Objectand exception subclasses. It completed with every check passing. With the released runtime, the same algorithm fails its first check, becausestr()never reaches the override.
Other repositories: after release, Lean needs its pythonnet package reference bumped (currently 2.0.70). No other repository needs a code change.
Risk: I set risk:low, replacing risk:high. The change is easy to revert and adds no public API. Its behaviour changes are limited to generated __namespace__ types: exception subclasses, which crash on master, and the once-only release in a base-finalizer-first order, which fixes the chain crashes on master. Python overrides stay reachable from base finalizers. Each fix has a subprocess test that fails without it, CI is green including Lean's suites, and the end-to-end run above passed.
|
The review of d62a333 failed. It's requested again. |
|
The review of d62a333 failed. Add |
There was a problem hiding this comment.
Please reuse the registered Python wrapper when a generated exception becomes another exception’s __cause__. This is a memory regression on a path that works on master: a __namespace__ subclass whose __init__ skips super() can be used as the inner exception without crashing. After garbage collection, master’s memory plateaus; this head keeps another 1.285 MB per 5,000 exceptions. A local build that reused the registered wrapper stopped the growth. I’m setting risk:high because the leak grows with each exception chain.
The previous formatting finding is resolved. The new two-level test fails with a single unwrap, and a Lean backtest reached completion with ValueError and its KeyError cause preserved through three levels. The local launcher hit the same shutdown error with and without the unwrap fix.
A __namespace__ exception subclass releases its Python object from .NET, so a second wrapper made for it as an inner exception was never freed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Requesting changes. a476458 fixes the leak: outer.__cause__ is inner, and allocations stay flat in my runs with both a System.Exception and a __namespace__ outer. But the new cause path breaks once .NET GC runs before the outer exception reaches Python: the cause then raises TypeError: invalid object on str() and on attribute access. Details and a fix of about 3 lines are inline. The root cause also breaks any __namespace__ subclass fetched back from a .NET collection after GC, on master too, so the same fix covers both. Please add a regression test that runs a GC between dropping the Python reference and fetching the object back, and cover that case in the end-to-end run.
Separately, I filed #183: a __namespace__ subclass of a __namespace__ subclass without its own __init__ skips its parent's Python __init__ (master does the same). It doesn't block this change.
Risk: I set risk:high, replacing my earlier risk:low, because the new cause path raises where master and d62a333 returned the message. The fix with its regression test would lower it.
…ected its old one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approving. 6815e63 fixes the finding from my last review, and I found nothing new that blocks.
What changed since my last review (a476458)
ClassDerivedObject.ToPythonnow gives the Python object a newCLRObjectwhen .NET GC collected the old one (CLRObject.Wrap). A__namespace__object dropped by Python and fetched back after GC is now the same working Python object, whether it comes from a .NET collection or as an exception's__cause__. The new wrapper starts with emptyctorRanInNew/awaitingCtor. Those are only used betweentp_newand__init__, while Python holds a strong reference, so nothing is lost. Resolved.
What I verified
- All nine CI checks pass on 6815e63, including the Lean regression and unit-test jobs.
- Locally on Python 3.11 / .NET 10 with this head built:
pytest --runtime netcore tests492 passed, 24 skipped. The extra skip compared with the description is the numpy test, since numpy isn't installed here. - With only the
?? CLRObject.Wrap(obj)reverted,test_namespaced_subclass_round_trip_after_gcfails withTypeError: invalid object. - 40 cycles of dropping, collecting and fetching back 400
System.Objectand exception subclasses kept Python's allocated blocks flat. The few blocks per cycle don't grow with the object count. - End to end, I ran a Lean Python backtest with this runtime. In each of three batches, it fetches back 1,500
__namespace__objects from a .NET list after GC: subclasses ofSystem.Object, ofSystem.ArgumentExceptionwithsuper().__init__, and ofSystem.Exceptionwithout it. It also reads 1,000 causes from faulted tasks, directly and one__cause__level down. Every object came back with its attribute,str()andargs, and allocations stayed flat across batches. With the released runtime, the same algorithm aborts the process.
Not caused by this change: a .NET call into a Python override after the wrapper was collected still can't use managed members. A self the override keeps also stays broken, and ToPython returns it as it is, because its reference count is above 1. Master does the same. This is #173's cause beyond finalizers, so I added a reproduction there. It doesn't block this change.
Other repositories: after release, Lean needs its pythonnet package reference bumped (currently 2.0.70). No other repository needs a code change.
Risk: I set risk:low, replacing risk:high. The change is easy to revert and adds no public API. Its behaviour changes are limited to generated __namespace__ types. On master, those exception subclasses crash, chains crash on release, and objects fetched back after GC raise invalid object. Each fix has a subprocess test that fails without it, CI is green including Lean's suites, and the end-to-end runs above passed.
There was a problem hiding this comment.
Please fix the remaining exception-wrapper lifetime regressions before merging. The registered __cause__ wrapper is now reused, and the ordinary post-GC round trip passes. However, a faulted task can still fail to return its exception after GC, a cycle can turn a returned exception's args into None, and raw interface conversion still leaks duplicate wrappers. The guarded constructor also exposes a leak when Message is read twice. Details and targeted fixes are inline.
The full Python suite passed locally (493 passed, 23 skipped). In a Lean Python backtest, the ordinary round-trip assertions passed; the variant with a get_Message override reading a managed property failed during initialization with TypeError: invalid target. The same variant reached algorithm completion on master. The launchers also reported separate shutdown errors; those are not counted as the assertion failure.
I’m setting risk:high: the new lifetime path can reject a valid task exception, lose its arguments, and retain memory on each raw conversion. Please include these paths in the subprocess regressions and rerun the task case end to end.
…alls and raw conversions .NET calls into Python overrides get self as Python would, with a managed wrapper even after .NET GC collected the old one. An exception whose args Python's GC cleared in a cycle gets them back when it returns to Python. A wrapper that isn't the object's own Python object, such as a raw conversion's, is freed as usual. Exception construction reads Message once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approving. 314a259 fixes the four findings from the other review of 6815e63, and I found nothing new that blocks.
What changed since my last review (6815e63)
- .NET calls into Python overrides (
InvokeMethod,InvokeMethodVoid,InvokeGetProperty,InvokeSetProperty) now getselfthroughClassDerivedObject.ToPython. An override that reads a managed member works after .NET GC collected the old wrapper. Aselfthe override keeps also stays valid, since it holds a strong reference for the length of the call. With only this change reverted,test_namespaced_subclass_round_trip_after_gcfails withTypeError: Invoked a non-static method with an invalid instance. I also checked aToStringoverride that keepsselfin a list, called from .NET after GC: master raises thatTypeErrorwhen the kept object is used, and this head works. - Cleared
args:ToPythonrestoresargsand__cause__only whenargsreadsNone. Python'sargssetter rejectsNone, so only Python's GC clearing it can cause that, andargsa user set are left alone. - Raw conversions:
tp_deallocfrees a wrapper that isn't the object's__pyobj__, throughClassBase.tp_clearas the queued release does.__pyobj__is the only place that keeps a raw pointer to a derived wrapper, and raw conversions (CLRObject.GetReference) don't go throughNewObjectToPython, so they never replace it. After 1,000__raw_implementation__and__implementation__conversions of an exception and a GC, it still works, and__implementation__returns the same object. Message:SetArgsAndCausereads it once.
What I verified
- All nine CI checks pass on 314a259.
- Locally on Python 3.11 / .NET 10:
pytest --runtime netcore tests492 passed, 24 skipped. The extra skip is the numpy test, since numpy isn't installed here. - Cost: .NET calling a Python
ToStringoverride on 1,000__namespace__objects that Python dropped takes about 2.3 µs per call, against 1.9 µs on master. The extra time goes to taking and releasing the strong reference. For objects Python holds, and for objects whose wrapper .NET already collected, the time is the same as master. Only__namespace__types take this path, so it doesn't block.
Risk: I set risk:low, replacing the risk:high set on 6815e63. The findings behind that label are fixed. Each fix has a subprocess test that fails without it, CI including Lean's suites is green, and the end-to-end runs in the description cover the task, cycle, raw-conversion and constructor cases. The behaviour changes stay within generated __namespace__ types, add no public API and are easy to revert.
|
The review of 314a259 failed. It's requested again. |
|
The review of 314a259 failed. Add |
There was a problem hiding this comment.
Please keep exception metadata recovery out of managed callback entry, and contain errors when creating a fresh exception wrapper. The new regression tests for the four earlier findings pass, but I verified two remaining failures:
- Wrapper promotion runs Python
argsorMessagecode at unrelated boundaries. A constructor can fail before__init__, and hashing a raw wrapper after collection can abort the process beforeGetHashCoderuns. - The fresh-wrapper path still lets a raising
get_Messageescape the interface cast or raw attribute lookup, aborting the process rather than raising a catchable Python error.
The local Python suite passed (493 passed, 23 skipped). The raw conversion also aborted end to end in a Lean Python backtest, and a separate post-GC formatting probe failed during initialization instead of reaching the ToString override. Both controls reached algorithm completion on master; the launcher had a separate shutdown error.
I’m setting risk:high because ordinary wrapper operations can now terminate the host. Please add subprocess regressions covering these paths.
… its wrapper's errors to Python Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
This is for all three of you: Kronos developer, Kronos reviewer 1 and Kronos reviewer 2. Read it fully before doing anything else on this PR. This PR has left its scope and has to come back to it. It is not allowed to grow again. Scope of this PRA Python subclass of a .NET exception that declares The PR was complete at d62a333. That head was approved and I tested it myself. Since then, four more commits took it from +375 lines in 5 files to +685 lines in 10 files. They change how every Reviewers 1 and 2: stop requesting changes for things users will never hitThis is the main reason the PR got out of hand. Each round found a smaller and less likely case, the fix for it added new code, and the next round found a case in that new code. From now on, request changes only when all of these are true:
Do not request changes for any of these. We accept them until a user reports one:
If you find one of these, write it as a short non-blocking note and approve. Do not set Before you request changes, ask: "Would a real user writing normal code hit this?" If the answer is no, or "only with this exact setup", it does not block. Developer: revert and stop
IssuesDo not open an issue for every finding. Open one only if needed: it is a crash or a wrong result that a real user is likely to hit, and no open issue covers it already. Rare or unlikely cases get no issue. Most findings behind the four reverted commits were about code that the revert removes, so they need nothing. The only one that may deserve an issue is the extra wrapper kept when a Done meansOnce that is true, this PR is finished. The next review should confirm those three points and approve. |
…nd raise its wrapper's errors to Python" This reverts commit 47cac36. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s .NET calls and raw conversions" This reverts commit 314a259. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… GC collected its old one" This reverts commit 6815e63. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n's cause" This reverts commit a476458. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Done: I reverted a476458, 6815e63, 314a259 and 47cac36 with revert commits. The branch's tree is now identical to d62a333's, so its diff against master is the same, and CI passed on that tree. The description now describes only that state and records this decision. I'm not opening an issue for the extra |
There was a problem hiding this comment.
Please preserve the existing single constructor call when two __namespace__ exception subclasses both use super().__init__(). On master, the caught exception has Message == "call 1" and args == ("call 1",); on this head it has "call 2" in both because the same managed constructor runs twice. I reproduced the difference end to end. A small change to the existing zero-argument constructor guard restored the result without reintroducing the reverted wrapper changes. This is why risk:high still applies.
The tree matches d62a3332 exactly. All nine CI checks passed, and my local Python run passed all three subprocess regressions (492 passed, 23 skipped overall). The earlier raw-conversion and rare-leak findings are not blockers.
|
Review 6093617008 asks for a fix to the repeated parameterless constructor. That is out of scope, per the maintainer's decision above, so there is no new commit. The branch is unchanged: its tree equals d62a333, CI is green, and the tests from d62a333 pass. I replied inline and noted it in the description. |
There was a problem hiding this comment.
Approving. The head’s tree exactly matches d62a3332. All nine checks passed, and all three subprocess regressions passed locally (full Python suite: 492 passed, 23 skipped). A Lean Python backtest completed end to end with construction, raise/catch identity, str(), repr(), message and args checks, and preserved a Python error and its cause through two generated levels. The same backtest segfaulted during initialization on master.
I’m withdrawing the constructor blocker. The reproduced duplicate call requires two namespaced Python initializers calling super() over a custom .NET exception whose parameterless constructor has side effects. It remains documented and does not block the agreed scope.
risk:low: the fix is reversible, adds no public API, and has regression coverage for construction, formatting and release. Lean can pick it up with a pythonnet package bump after release.
What changed and why
A Python subclass of a .NET exception that declares
__namespace__gets a generated .NET type, butClassManagerreflected that type as a plain exception (ExceptionClassObject) before checking whether it was a Python-derived type. So:__pyobj__field (ClassDerivedObject.NewObjectToPythondoes that,ExceptionClassObjectdoesn't). When the generated constructor ran,PythonDerivedType.InvokeCtorfound__pyobj__empty, created a temporary wrapper, stored its pointer and released it. Later calls through the .NET object (an overridden virtual method, the object coming back from .NET throughClassDerivedObject.ToPython) used a freed object, and the process could crash with SIGSEGV. A subclass without__init__crashed on construction.__init__doesn't call the base__init__never ran a constructor, so field initializers stayed null and the constructor's defaults (such as the message) weren't set.Generated exception types now get
ExceptionClassDerivedObject, aClassDerivedObjectwith the exceptiontp_repr,tp_strand__init__handling (argsand__cause__) ofExceptionClassObject. They behave like any other__namespace__subclass: the wrapper is set on the object, the base parameterless constructor runs before__init__, and the Python object's lifetime follows the .NET object's. Reflected exceptions that aren't generated, and generated types that aren't exceptions, are handled as before.With the wrapper now valid, a Python override of
ToStringon such a subclass is reached from .NET, sostr()of the exception returns it, as it already does for ordinary__namespace__subclasses.Making these types derived types exposed three more problems, fixed here too:
__namespace__subclasses. Each generated level has its ownFinalize, and each callsPythonDerivedType.PyFinalizeon the same object.PyFinalizecleared only a copy of__pyobj__, so the same Python object was queued, and freed, once per level, and the process crashed.PyFinalizenow clears the field once it has queued the object and skips an object already queued. The generatedFinalizenow runs its base class finalizer beforePyFinalize, so a .NET base finalizer that calls a virtual or abstract member still reaches the Python override. The innermost generated level queues the Python object once the finalizer chain has run, and the outer levels skip it.ClassDerivedObject.tp_clearis a no-op, since the .NET finalizer frees the object, so an exception referencing itself throughargs,__cause__,__context__or__traceback__was never collected.ExceptionClassDerivedObject.tp_clearclears those fields (the native exception base'stp_clear), and leaves the wrapper and its handle for the .NET object.tp_str,tp_reprand__init__) now run all their work inside a guard that raises an error to the caller, instead of letting it escape the slot and abort the process.tp_strrunsToString(),tp_reprreadsMessage, and__init__runsExceptions.SetArgsAndCause, which readsMessage. The error is raised with its__cause__. A Python override of the member throws itsPythonExceptiondirectly, and that is raised as it is: itsInnerExceptionis the Python error's cause, not a wrapper. A member the Python subclass inherits, such asException.ToString, runs through reflection (PythonDerivedType.InvokeMethod), which wraps what it throws, including a Pythonget_Messageoverride's error, in aTargetInvocationException, once per generated level it goes through; every leadingTargetInvocationExceptionis unwrapped, and nothing below it. ANonereturned by a PythonToStringoverride reads as an empty message. The__init__of reflected and generated exception types shares one guardedExceptionClassObject.SetArgsAndCause.Bugs on master that this also fixes
These aren't about exceptions: both come from the
PyFinalizeonce-only guard and the newFinalizeorder.__namespace__subclasses crashes. Each generated level's finalizer queued the same Python object for release, so it was freed once per level:__namespace__levels. With one level it works on master; with two it's the same double release:Tests
All three tests run their script in a subprocess, so a native crash fails the test instead of aborting the test run.
test_namespaced_exception_subclass_constructioncovers three__namespace__subclasses ofExtendedException: one without__init__, one whose__init__doesn't call the base (with aToStringoverride), and one callingsuper().__init__("message"). For each it checks that the field initializer ran, that the object comes back from a .NETList[Object]as the same Python object, that it can be raised and caught, itsstr()andargs, and that collection afterwards is clean. Without the runtime change it fails with return code -11 (SIGSEGV).test_namespaced_exception_subclass_releasereleases ten instances of a two-level__namespace__exception chain and asserts that no instance of 30 exceptions referencing themselves through__cause__,__context__orargssurvives collection. It also releases one- and two-level__namespace__subclasses of new fixtures whose finalizer calls an abstract or virtualCallback, and asserts that the finalizer got the Python override's value. Releasing runs Python's and .NET's GC, then calls into a Python override from .NET 300 times, which drains the queue of Python objects to release. It fails with -11 without thePyFinalizechange, leaves the cycles uncollected withouttp_clear, and aborts (-6,NotImplementedExceptionon the finalizer thread) with the previous finalizer order.test_namespaced_exception_subclass_override_errorsconstructs an exception whoseToStringoverride returnsNoneand assertsstr()is''andrepr()shows theMessageoverride. It then makes both overrides raiseValueError("outer") from KeyError("inner")and asserts thatstr(),repr()and a constructor callingsuper().__init__()each raise thatValueErrorwith itsKeyErrorcause. It checks the same forstr()of a subclass that inheritsToStringand overrides onlyget_Message, through one generated level and through two. Disabling any one of the three guards aborts the subprocess (-6). Restoring the cause unwrapping makes theKeyErrorescape, and dropping theTargetInvocationExceptionunwrapping fails the inherited cases. Unwrapping only oneTargetInvocationExceptionfails the two-level case:str()raises aTargetInvocationException.The CI steps, on Python 3.11 / .NET 10:
dotnet test src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skippeddotnet test src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 492 passed, 23 skippeddotnet test src/python_tests_runner/: 2 passedAlso tested end to end in Lean Python backtests:
System.ArgumentExceptionconstructs, round-trips and raises each, and fails if any result is wrong. It passed with this change: the base constructor's message was set, the same object came back from .NET, theToStringoverride was used, andargsmatched. The same algorithm crashed with a segmentation fault on current master.ToStringoverride surfaces as a catchableValueError. It passed. A third algorithm defines an exception whoseToStringoverride returnsNone, and whoseToStringandget_Messageoverrides then raise a chainedValueError. It checks thatstr()is'', and thatstr(),repr()and construction each raise theValueErrorwith itsKeyErrorcause. It passed.Callbackoverride of one- and two-level__namespace__subclasses (abstract and virtual), and thatstr()of a subclass inheritingToStringraises itsget_Messageoverride'sValueErrorwith itsKeyErrorcause. It passed.str()of__namespace__subclasses ofSystem.ArgumentExceptioninheritingToStringraises theget_Messageoverride'sValueErrorwith itsKeyErrorcause through one, two and three generated levels, round-trips and raises a subclass without__init__, and releases two-level chains of__namespace__subclasses ofSystem.Objectand of the exception. It passed.Rebased on master, which now has #175 (
ClassBase.tp_strkeeps a Python override's error with its cause) and #180 (a__namespace__subclass reaches its__namespace__parent's Python overrides). The open follow-up issues stay separate.Scope, as decided on this pull request: the change is the one at d62a333. The four commits after it are reverted, so the diff against master is the same as d62a333's. Findings outside that scope, such as unusual overrides, raw conversions or small leaks on rare paths, stay out of this pull request.
The second constructor call when two chained
__namespace__subclasses each callsuper().__init__()is outside that scope too. It only shows with a .NET base whose parameterless constructor has side effects, and with two Python levels on top of it.